package com.qkjia.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.ArrayList;
import java.util.Properties;

/**
 * @Auther 赵乾坤
 * @Date 2021-10-01 21:37
 * 带拦截器的生产者
 */
public class InterceptotProducer {
    public static void main(String[] args) throws InterruptedException {
        // 1.创建kafka生产者的配置信息
        Properties properties = new Properties();

        // 添加kafka配置信息
        // 2.指定连接的kafka集群
//        properties.put("bootstrap.servers", "hadoop102:9092");
//        properties.put("bootstrap.servers", "127.0.0.1:9092");
        properties.put("bootstrap.servers", "8.135.84.118:9092");
//        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092");
        // 3.ACK应答级别
        properties.put("acks", "all");
//        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        // 4.重试次数
        properties.put("retries", 1);
        // 5.批次大小 16k
        properties.put("batch.size", 16384);
        // 6.等待时间
        properties.put("linger.ms", 1);
        // 7.RecordAccumulator缓冲区大小 32M
        properties.put("buffer.memory", 33554432);

        // 8.key value的序列号类
        properties.put("key.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");

        properties.put("value.serializer",
                "org.apache.kafka.common.serialization.StringSerializer");

        // 添加拦截器
        ArrayList<String> interceptors = new ArrayList<>();
        interceptors.add("com.qkjia.interceptor.TimeInterceptor");
        interceptors.add("com.qkjia.interceptor.CounterInterceptor");
        properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, interceptors);
        // 9.创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        // 10.发送数据
        for (int i = 0; i < 10; i++) {
            producer.send(new ProducerRecord<String, String>("first", "atguigu--" + i));
        }

        // 睡5秒
        Thread.sleep(5000);
        System.out.println("***************************************");

        // 11.关闭资源
        producer.close();
    }
}
